package com.mojo.web.config;

import com.mojo.web.converter.MyConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.accept.ParameterContentNegotiationStrategy;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
@Configuration
public class WebConfigurer {
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
                //自定义扩展messageConverter
                MyConverter converter = new MyConverter();
                converters.add(converter);

            }

            @Override
            public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
                //参数内容协商配置
                HashMap<String, MediaType> map = new HashMap<>();
                map.put("json", MediaType.APPLICATION_JSON);
                map.put("xml", MediaType.APPLICATION_XML);
                map.put("mojo", MediaType.parseMediaType("application/x-mojo"));
                ParameterContentNegotiationStrategy strategy = new ParameterContentNegotiationStrategy(map);
                //支持请求头内容协商
                HeaderContentNegotiationStrategy headerStrategy = new HeaderContentNegotiationStrategy();
                configurer.strategies(Arrays.asList(headerStrategy, strategy));
            }
        };
    }
}
